{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "N6ZDpd9XzFeN"
      },
      "source": [
        "##### Copyright 2018 The TensorFlow Hub Authors.\n",
        "\n",
        "Licensed under the Apache License, Version 2.0 (the \"License\");"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "form",
        "colab": {},
        "colab_type": "code",
        "id": "KUu4vOt5zI9d"
      },
      "outputs": [],
      "source": [
        "# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     http://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License.\n",
        "# =============================================================================="
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ok9PfyoQ2rH_"
      },
      "source": [
        "# How to build a simple text classifier with TF-Hub\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Kzz1rsXKNLww"
      },
      "source": [
        "\u003e Note: This tutorial uses **deprecated** TensorFlow 1 functionality. For a modern approach to this task, see the [TensorFlow 2 version](https://www.tensorflow.org/hub/tutorials/tf2_text_classification).\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/hub/blob/master/docs/tutorials/text_classification_with_tf_hub.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/hub/blob/master/docs/tutorials/text_classification_with_tf_hub.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "AK3mz3JNMW8Y"
      },
      "source": [
        "TF-Hub is a platform to share machine learning expertise packaged in reusable resources, notably pre-trained **modules**. This tutorial is organized into two main parts.\n",
        "\n",
        "**Introduction:** Training a text classifier with TF-Hub\n",
        "\n",
        "We will use a TF-Hub text embedding module to train a simple sentiment classifier with a reasonable baseline accuracy. We will then analyze the predictions to make sure our model is reasonable and propose improvements to increase the accuracy.\n",
        "\n",
        "**Advanced:** Transfer learning analysis\n",
        "\n",
        "In this section, we will use various TF-Hub modules to compare their effect on the accuracy of the estimator and demonstrate advantages and pitfalls of transfer learning.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "aYVd26q1_3xW"
      },
      "source": [
        "## Optional prerequisites\n",
        "\n",
        "* Basic understanding of Tensorflow [premade estimator framework](https://www.tensorflow.org/get_started/premade_estimators).\n",
        "* Familiarity with [Pandas](https://pandas.pydata.org/) library.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "xOATihhH1IxS"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "code",
        "colab": {},
        "colab_type": "code",
        "id": "_8N3Hx2dyUC-"
      },
      "outputs": [],
      "source": [
        "# Install TF-Hub.\n",
        "!pip install seaborn"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "tRXN9a8Mz8e-"
      },
      "source": [
        "More detailed information about installing Tensorflow can be found at [https://www.tensorflow.org/install/](https://www.tensorflow.org/install/)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "v7hy0bhngTUp"
      },
      "outputs": [],
      "source": [
        "from absl import logging\n",
        "\n",
        "import tensorflow as tf\n",
        "import tensorflow_hub as hub\n",
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import os\n",
        "import pandas as pd\n",
        "import re\n",
        "import seaborn as sns"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "6OPyVxHuiTEE"
      },
      "source": [
        "# Getting started\n",
        "\n",
        "## Data\n",
        "We will try to solve the [Large Movie Review Dataset v1.0](http://ai.stanford.edu/~amaas/data/sentiment/) task [(Mass et al., 2011)](http://ai.stanford.edu/~amaas/papers/wvSent_acl2011.pdf). The dataset consists of IMDB movie reviews labeled by positivity from 1 to 10. The task is to label the reviews as **negative** or **positive**."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "both",
        "colab": {},
        "colab_type": "code",
        "id": "rKzc-fOGV72G"
      },
      "outputs": [],
      "source": [
        "# Load all files from a directory in a DataFrame.\n",
        "def load_directory_data(directory):\n",
        "  data = {}\n",
        "  data[\"sentence\"] = []\n",
        "  data[\"sentiment\"] = []\n",
        "  for file_path in os.listdir(directory):\n",
        "    with tf.io.gfile.GFile(os.path.join(directory, file_path), \"r\") as f:\n",
        "      data[\"sentence\"].append(f.read())\n",
        "      data[\"sentiment\"].append(re.match(\"\\d+_(\\d+)\\.txt\", file_path).group(1))\n",
        "  return pd.DataFrame.from_dict(data)\n",
        "\n",
        "# Merge positive and negative examples, add a polarity column and shuffle.\n",
        "def load_dataset(directory):\n",
        "  pos_df = load_directory_data(os.path.join(directory, \"pos\"))\n",
        "  neg_df = load_directory_data(os.path.join(directory, \"neg\"))\n",
        "  pos_df[\"polarity\"] = 1\n",
        "  neg_df[\"polarity\"] = 0\n",
        "  return pd.concat([pos_df, neg_df]).sample(frac=1).reset_index(drop=True)\n",
        "\n",
        "# Download and process the dataset files.\n",
        "def download_and_load_datasets(force_download=False):\n",
        "  dataset = tf.keras.utils.get_file(\n",
        "      fname=\"aclImdb.tar.gz\", \n",
        "      origin=\"http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\", \n",
        "      extract=True)\n",
        "  \n",
        "  train_df = load_dataset(os.path.join(os.path.dirname(dataset), \n",
        "                                       \"aclImdb\", \"train\"))\n",
        "  test_df = load_dataset(os.path.join(os.path.dirname(dataset), \n",
        "                                      \"aclImdb\", \"test\"))\n",
        "  \n",
        "  return train_df, test_df\n",
        "\n",
        "# Reduce logging output.\n",
        "logging.set_verbosity(logging.ERROR)\n",
        "\n",
        "train_df, test_df = download_and_load_datasets()\n",
        "train_df.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "D9Xq4x1mU3un"
      },
      "source": [
        "## Model\n",
        "### Input functions\n",
        "\n",
        "[Estimator framework](https://www.tensorflow.org/get_started/premade_estimators#overview_of_programming_with_estimators) provides [input functions](https://www.tensorflow.org/api_docs/python/tf/compat/v1/estimator/inputs/pandas_input_fn) that wrap Pandas dataframes."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "both",
        "colab": {},
        "colab_type": "code",
        "id": "25rdoEHih0fm"
      },
      "outputs": [],
      "source": [
        "# Training input on the whole training set with no limit on training epochs.\n",
        "train_input_fn = tf.compat.v1.estimator.inputs.pandas_input_fn(\n",
        "    train_df, train_df[\"polarity\"], num_epochs=None, shuffle=True)\n",
        "\n",
        "# Prediction on the whole training set.\n",
        "predict_train_input_fn = tf.compat.v1.estimator.inputs.pandas_input_fn(\n",
        "    train_df, train_df[\"polarity\"], shuffle=False)\n",
        "# Prediction on the test set.\n",
        "predict_test_input_fn = tf.compat.v1.estimator.inputs.pandas_input_fn(\n",
        "    test_df, test_df[\"polarity\"], shuffle=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Uyl6YGRcVAwP"
      },
      "source": [
        "### Feature columns\n",
        "\n",
        "TF-Hub provides a [feature column](https://www.tensorflow.org/hub/api_docs/python/hub/text_embedding_column.md) that applies a module on the given text feature and passes further the outputs of the module. In this tutorial we will be using the [nnlm-en-dim128 module](https://tfhub.dev/google/nnlm-en-dim128/1). For the purpose of this tutorial, the most important facts are:\n",
        "\n",
        "* The module takes **a batch of sentences in a 1-D tensor of strings** as input.\n",
        "* The module is responsible for **preprocessing of sentences** (e.g. removal of punctuation and splitting on spaces).\n",
        "* The module works with any input (e.g. **nnlm-en-dim128** hashes words not present in vocabulary into ~20.000 buckets)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "X7vyvj-hDEXu"
      },
      "outputs": [],
      "source": [
        "embedded_text_feature_column = hub.text_embedding_column(\n",
        "    key=\"sentence\", \n",
        "    module_spec=\"https://tfhub.dev/google/nnlm-en-dim128/1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "YPuHgx3BWBOg"
      },
      "source": [
        "### Estimator\n",
        "\n",
        "For classification we can use a [DNN Classifier](https://www.tensorflow.org/api_docs/python/tf/estimator/DNNClassifier) (note further remarks about different modelling of the label function at the end of the tutorial)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "23U30yEkVq4w"
      },
      "outputs": [],
      "source": [
        "estimator = tf.estimator.DNNClassifier(\n",
        "    hidden_units=[500, 100],\n",
        "    feature_columns=[embedded_text_feature_column],\n",
        "    n_classes=2,\n",
        "    optimizer=tf.keras.optimizers.Adagrad(lr=0.003))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-O_k-8jgWPXY"
      },
      "source": [
        "### Training\n",
        "\n",
        "Train the estimator for a reasonable amount of steps."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "e5uDRv1r7Ed4"
      },
      "outputs": [],
      "source": [
        "# Training for 5,000 steps means 640,000 training examples with the default\n",
        "# batch size. This is roughly equivalent to 25 epochs since the training dataset\n",
        "# contains 25,000 examples.\n",
        "estimator.train(input_fn=train_input_fn, steps=5000);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "s8j7YTRSe7Pj"
      },
      "source": [
        "# Prediction\n",
        "\n",
        "Run predictions for both training and test set."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "zbLg5LzGwAfC"
      },
      "outputs": [],
      "source": [
        "train_eval_result = estimator.evaluate(input_fn=predict_train_input_fn)\n",
        "test_eval_result = estimator.evaluate(input_fn=predict_test_input_fn)\n",
        "\n",
        "print(\"Training set accuracy: {accuracy}\".format(**train_eval_result))\n",
        "print(\"Test set accuracy: {accuracy}\".format(**test_eval_result))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "DR2IsTF5vuAX"
      },
      "source": [
        "## Confusion matrix\n",
        "\n",
        "We can visually check the confusion matrix to understand the distribution of misclassifications."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "nT71CtArpsKz"
      },
      "outputs": [],
      "source": [
        "def get_predictions(estimator, input_fn):\n",
        "  return [x[\"class_ids\"][0] for x in estimator.predict(input_fn=input_fn)]\n",
        "\n",
        "LABELS = [\n",
        "    \"negative\", \"positive\"\n",
        "]\n",
        "\n",
        "# Create a confusion matrix on training data.\n",
        "cm = tf.math.confusion_matrix(train_df[\"polarity\"], \n",
        "                              get_predictions(estimator, predict_train_input_fn))\n",
        "\n",
        "# Normalize the confusion matrix so that each row sums to 1.\n",
        "cm = tf.cast(cm, dtype=tf.float32)\n",
        "cm = cm / tf.math.reduce_sum(cm, axis=1)[:, np.newaxis]\n",
        "\n",
        "sns.heatmap(cm, annot=True, xticklabels=LABELS, yticklabels=LABELS);\n",
        "plt.xlabel(\"Predicted\");\n",
        "plt.ylabel(\"True\");"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "sG-ES55Ftp-t"
      },
      "source": [
        "# Further improvements\n",
        "\n",
        "1. **Regression on sentiment**: we used a classifier to assign each example into a polarity class. But we actually have another categorical feature at our disposal - sentiment. Here classes actually represent a scale and the underlying value (positive/negative) could be well mapped into a continuous range. We could make use of this property by computing a regression ([DNN Regressor](https://www.tensorflow.org/api_docs/python/tf/contrib/learn/DNNRegressor)) instead of a classification ([DNN Classifier](https://www.tensorflow.org/api_docs/python/tf/contrib/learn/DNNClassifier)).\n",
        "2. **Larger module**: for the purposes of this tutorial we used a small module to restrict the memory use. There are modules with larger vocabularies and larger embedding space that could give additional accuracy points.\n",
        "3. **Parameter tuning**: we can improve the accuracy by tuning the meta-parameters like the learning rate or the number of steps, especially if we use a different module. A validation set is very important if we want to get any reasonable results, because it is very easy to set-up a model that learns to predict the training data without generalizing well to the test set.\n",
        "4. **More complex model**: we used a module that computes a sentence embedding by embedding each individual word and then combining them with average. One could also use a sequential module (e.g. [Universal Sentence Encoder](https://tfhub.dev/google/universal-sentence-encoder/2) module) to better capture the nature of sentences. Or an ensemble of two or more TF-Hub modules.\n",
        "5. **Regularization**: to prevent overfitting, we could try to use an optimizer that does some sort of regularization, for example [Proximal Adagrad Optimizer](https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/ProximalAdagradOptimizer).\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "fKRNsaO8L50F"
      },
      "source": [
        "# Advanced: Transfer learning analysis\n",
        "\n",
        "Transfer learning makes it possible to **save training resources** and to achieve good model generalization even when **training on a small dataset**. In this part, we will demonstrate this by training with two different TF-Hub modules:\n",
        "\n",
        "* **[nnlm-en-dim128](https://tfhub.dev/google/nnlm-en-dim128/1)** - pretrained text embedding module,\n",
        "* **[random-nnlm-en-dim128](https://tfhub.dev/google/random-nnlm-en-dim128/1)** - text embedding module that has same vocabulary and network as **nnlm-en-dim128**, but the weights were just randomly initialized and never trained on real data.\n",
        "\n",
        "And by training in two modes: \n",
        "\n",
        "* training **only the classifier** (i.e. freezing the module), and \n",
        "* training the **classifier together with the module**.\n",
        "\n",
        "Let's run a couple of trainings and evaluations to see how using a various modules can affect the accuracy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "AWYa1So1ARyz"
      },
      "outputs": [],
      "source": [
        "def train_and_evaluate_with_module(hub_module, train_module=False):\n",
        "  embedded_text_feature_column = hub.text_embedding_column(\n",
        "      key=\"sentence\", module_spec=hub_module, trainable=train_module)\n",
        "\n",
        "  estimator = tf.estimator.DNNClassifier(\n",
        "      hidden_units=[500, 100],\n",
        "      feature_columns=[embedded_text_feature_column],\n",
        "      n_classes=2,\n",
        "      optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.003))\n",
        "\n",
        "  estimator.train(input_fn=train_input_fn, steps=1000)\n",
        "\n",
        "  train_eval_result = estimator.evaluate(input_fn=predict_train_input_fn)\n",
        "  test_eval_result = estimator.evaluate(input_fn=predict_test_input_fn)\n",
        "\n",
        "  training_set_accuracy = train_eval_result[\"accuracy\"]\n",
        "  test_set_accuracy = test_eval_result[\"accuracy\"]\n",
        "\n",
        "  return {\n",
        "      \"Training accuracy\": training_set_accuracy,\n",
        "      \"Test accuracy\": test_set_accuracy\n",
        "  }\n",
        "\n",
        "\n",
        "results = {}\n",
        "results[\"nnlm-en-dim128\"] = train_and_evaluate_with_module(\n",
        "    \"https://tfhub.dev/google/nnlm-en-dim128/1\")\n",
        "results[\"nnlm-en-dim128-with-module-training\"] = train_and_evaluate_with_module(\n",
        "    \"https://tfhub.dev/google/nnlm-en-dim128/1\", True)\n",
        "results[\"random-nnlm-en-dim128\"] = train_and_evaluate_with_module(\n",
        "    \"https://tfhub.dev/google/random-nnlm-en-dim128/1\")\n",
        "results[\"random-nnlm-en-dim128-with-module-training\"] = train_and_evaluate_with_module(\n",
        "    \"https://tfhub.dev/google/random-nnlm-en-dim128/1\", True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "CsWppYMphIPh"
      },
      "source": [
        "Let's look at the results."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "UVkdErEKkIXL"
      },
      "outputs": [],
      "source": [
        "pd.DataFrame.from_dict(results, orient=\"index\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Z9rZ2fuGfUFh"
      },
      "source": [
        "We can already see some patterns, but first we should establish the baseline accuracy of the test set - the lower bound that can be achieved by outputting only the label of the most represented class:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "IgYPVvc3G6OS"
      },
      "outputs": [],
      "source": [
        "estimator.evaluate(input_fn=predict_test_input_fn)[\"accuracy_baseline\"]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "UN4D-DPPrINX"
      },
      "source": [
        "Assigning the most represented class will give us accuracy of **50%**. There are a couple of things to notice here:\n",
        "\n",
        "1. Maybe surprisingly, **a model can still be learned on top of fixed, random embeddings**. The reason is that even if every word in the dictionary is mapped to a random vector, the estimator can separate the space purely using its fully connected layers.\n",
        "2. Allowing training of the module with **random embeddings** increases both training and test accuracy as oposed to training just the classifier.\n",
        "3. Training of the module with **pre-trained embeddings** also increases both accuracies. Note however the overfitting on the training set. Training a pre-trained module can be dangerous even with regularization in the sense that the embedding weights no longer represent the language model trained on diverse data, instead they converge to the ideal representation of the new dataset."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "N6ZDpd9XzFeN"
      ],
      "name": "Text classification with TF-Hub",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
